//
//  Kylin_AllTableViewController.m
//  03-BuDeJie
//
//  Created by Kylin on 16/2/25.
//  Copyright © 2016年 kylin. All rights reserved.
//

#import "Kylin_TopicViewController.h"
#import <AFNetworking.h>
#import <MJExtension.h>
#import <UIImageView+WebCache.h>
#import <SVProgressHUD.h>
#import "Kylin_TopicCell.h"

@interface  Kylin_TopicViewController()

/**manager*/
@property(nonatomic,strong)AFHTTPSessionManager *manager;

/**当前最后一个帖子的信息,用来加载更多的数据*/
@property(nonatomic,copy)NSString *maxTime;
/**TopicsArray Topics模型数据 强转告诉数组的类型*/
@property(nonatomic,strong)NSMutableArray<Kylin_TopicItem *> *topics;

/**头部view*/
@property(nonatomic,weak)UIView *header;
@property(nonatomic,weak)UILabel *headerLabel;
@property(nonatomic,assign,getter=isHeaderRefrshing)BOOL headerRefrshing;

/**尾部view*/
@property(nonatomic,weak)UIView *footer;
@property(nonatomic,weak)UILabel *footerLabel;
@property(nonatomic,assign,getter=isFooterRefrshing)BOOL footerRefrshing;

// 记录indicator状态
/**indicator*/
@property(nonatomic,weak)UIActivityIndicatorView *headerIndicator;
@property(nonatomic,weak)UIActivityIndicatorView *footerIndicator;


@end
static NSString *const Kylin_topicCellID = @"Kylin_TopicCell";
@implementation Kylin_TopicViewController

// 写该方法只为消除警告
- (Kylin_TopicType)type {return 0;}

- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}

#pragma mark- ViewDidLoad 初如化加载
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.backgroundColor = Kylin_Color(215, 215, 215);
    self.tableView.estimatedRowHeight = 160;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([Kylin_TopicCell class]) bundle:nil] forCellReuseIdentifier:Kylin_topicCellID];
    
    // 设置tableView ContentInset 实现穿透效果
    self.tableView.contentInset = UIEdgeInsetsMake(Kylin_NavBarMaxY + Kylin_TitleViewH , 0, Kylin_TabBarH, 0);
    
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    
    // 监听tabBarButton重复点击
    [self monitoringTabBarButton];
    
    // 刷新控件
    [self setupRefresh];
    
}

// 刷新控件
- (void)setupRefresh{
    
    // 添加广告控件
    UILabel *adLabel = [[UILabel alloc]init];
    adLabel.frame = CGRectMake(0, 0, self.tableView.width, 25);
    adLabel.text = @"广告";
    adLabel.textAlignment = NSTextAlignmentCenter;
    adLabel.backgroundColor = [UIColor darkGrayColor];
    self.tableView.tableHeaderView = adLabel;
    
    // 下拉刷新条
    UIView *header = [[UIView alloc]init];
    header.backgroundColor = [UIColor redColor];
    header.frame = CGRectMake(0, -50, self.tableView.width, 50);
    [self.tableView addSubview:header];
    self.header = header;
    
    // 文字
    UILabel *headerLabel = [[UILabel alloc]init];
    headerLabel.frame = header.bounds;
    headerLabel.backgroundColor = [UIColor redColor];
    headerLabel.text = @"下拉可以刷新";
    headerLabel.textAlignment = NSTextAlignmentCenter;
    [header addSubview:headerLabel];
    self.headerLabel = headerLabel;
    
    // 转圈圈
    UIActivityIndicatorView *headerIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    headerIndicator.frame = CGRectMake(header.width * 0.25,header.centerY + self.header.height, 0, 0);
    [header addSubview:headerIndicator];
    self.headerIndicator = headerIndicator;
    
    
    
    // 自动刷新
    [self headerBeginRefrshing];
    
    // 上拉刷新条
    UIView *footer = [[UIView alloc]init];
    footer.backgroundColor = [UIColor grayColor];
    footer.frame = CGRectMake(0, 0, self.tableView.width, 50);
    self.tableView.tableFooterView = footer;
    footer.hidden = YES;
    self.footer = footer;
    
    UILabel *footerLabel = [[UILabel alloc]init];
    footerLabel.frame = footer.bounds;
    footerLabel.text = @"上拉可以刷新";
    footerLabel.textAlignment = NSTextAlignmentCenter;
    [footer addSubview:footerLabel];
    self.footerLabel = footerLabel;
    // 转圈圈
    UIActivityIndicatorView *footerIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    footerIndicator.frame = CGRectMake(footer.width * 0.25,footer.centerY - self.footer.height * 0.5, 0, 0);
    [footer addSubview:footerIndicator];
    self.footerIndicator = footerIndicator;
    
    
}

#pragma mark- 加载服务器数据

- (void)loadNewTopics{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"data";
    parameters[@"type"]  = @(self.type);
    
    // 发送请求
    [self.manager GET:Kylin_RequestURL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        Kylin_AFNriteToPlist(topic)
        // 存储maxTime
        self.maxTime = responseObject[@"info"][@"maxtime"];
        // 字典转模型
        self.topics = [Kylin_TopicItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        // 刷新数据
        [self.tableView reloadData];
        
        [self headerEndRefrshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 结束刷新
        [self headerEndRefrshing];
        if (error.code == NSURLErrorCancelled) {
            Kylin_Log(@"刷新失败");
        }else{
            [SVProgressHUD showErrorWithStatus:@"网络繁忙，请稍后再试！"];
        }
        
    }];
    
}
- (void)loadMoreTopics{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"a"] = @"list";
    parameters[@"c"] = @"data";
    parameters[@"type"]  = @(self.type);
    parameters[@"maxtime"]= self.maxTime;
    
    // 发送请求
    [self.manager GET:Kylin_RequestURL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 存储maxTime
        self.maxTime = responseObject[@"info"][@"maxtime"];
        
        // 字典转模型
        NSArray *moreTopics = [Kylin_TopicItem mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        // 增加新数据
        [self.topics addObjectsFromArray:moreTopics];
        // 刷新数据
        [self.tableView reloadData];
        
        [self footerEndRefrshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self footerEndRefrshing];
        Kylin_Log(@"刷新失败");
    }];
}
#pragma mark- 监听tabBarButton重复点击相关代码
- (void)monitoringTabBarButton{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tabBarButtonDidClick) name:Kylin_tabBarButtonDidRepeatClickNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(titleButtonDidClick) name:Kylin_titleButtonDidRepeatClickNotification object:nil];
}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)titleButtonDidClick{
    
    [self tabBarButtonDidClick];
}
// 监听tabarButton的重复点击
- (void)tabBarButtonDidClick{
    // 如果当前控制器的view不在window上面，就直接返回
    if (self.tableView.window == nil)return;
    // 如果当前控制器的view没有跟window重叠
    if (self.tableView.scrollsToTop == NO) return;
    
    [self headerBeginRefrshing];
    //    Kylin_Log(@"刷新数据%@",self.class);
}

#pragma mark- delegate Method

// 计算cell 高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //
    //    Kylin_TopicItem *item = self.topics[indexPath.row];
    //    return item.cellHeight;
    return self.topics[indexPath.row].cellHeight;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    // 处理下刷新
    [self dealHeader];
    // 处理上拉刷新
    [self dealFooter];
    
    // 清除图片缓存
    [[SDImageCache sharedImageCache]clearMemory];
}

// 手松开的时侯调用这个方法
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (self.headerRefrshing) return;
    
    // 如果偏移量 <= offsetY, 就说明header已经完全出现
    CGFloat offsetY = -(self.tableView.contentInset.top + self.header.height);
    if (self.tableView.contentOffset.y <= offsetY) {
        [self headerBeginRefrshing];
    }
    
    
}

- (void)dealHeader{
    
    // header 还没有创建直接返回
    if (self.header == nil) return;
    if (self.isHeaderRefrshing) return;
    
    
    // 如果偏移量 <= offsetY, 就说明header已经完全出现
    CGFloat offsetY = -(self.tableView.contentInset.top + self.header.height);
    if (self.tableView.contentOffset.y <= offsetY) {
        self.headerLabel.text = @"松开立即刷新";
        self.headerLabel.backgroundColor = [UIColor blueColor];
    }else{
        
        self.headerLabel.text = @"下拉可以刷新";
        self.headerLabel.backgroundColor = [UIColor redColor];
    }
}

- (void)dealFooter{
    
    if (self.topics.count == 0) return;
    if (self.isFooterRefrshing) return;
    
    // 如果偏移量 >= offsetY, 就说明footer已经完全出现
    CGFloat offsetY = (self.tableView.contentSize.height + self.tableView.contentInset.bottom - self.tableView.height);
    if (self.tableView.contentOffset.y >= offsetY) {
        [self footerBeginRefrshing];
    }
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    // footerView的显示情况
    self.footer.hidden = (self.topics.count == 0);
    return self.topics.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    Kylin_TopicCell *cell = [tableView dequeueReusableCellWithIdentifier:Kylin_topicCellID];
    
    Kylin_TopicItem *topicItem = self.topics[indexPath.row];
    
    // 调整调用顺序,先计算好高度
    [topicItem cellHeight];
    
    cell.topicItem = topicItem;
    return cell;
}


#pragma mark- 刷新方法
- (void)headerBeginRefrshing{
    
    if (self.isHeaderRefrshing) return;
    
    // 进入刷新状态
    [self.headerIndicator startAnimating];
    self.headerLabel.text = @"正在刷新...";
    self.headerLabel.backgroundColor = [UIColor orangeColor];
    self.headerRefrshing = YES;
    
    // 增大内边距
    [UIView animateWithDuration:0.25 animations:^{
        UIEdgeInsets inset = self.tableView.contentInset;
        inset.top += self.header.height;
        self.tableView.contentInset = inset;
        self.tableView.contentOffset = CGPointMake(self.tableView.contentOffset.x, -inset.top);
    }];
    
    // 加载最新的子数据
    [self loadNewTopics];
}

- (void)headerEndRefrshing{
    self.headerRefrshing = NO;
    [self.headerIndicator stopAnimating];
    // 恢复内边距
    [UIView animateWithDuration:0.25 animations:^{
        UIEdgeInsets inset = self.tableView.contentInset;
        inset.top -= self.header.height;
        self.tableView.contentInset = inset;
    }];
}
- (void)footerBeginRefrshing{
    if (self.isFooterRefrshing) return;
    if (self.isHeaderRefrshing) return;
    
    [self.footerIndicator startAnimating];
    self.footerLabel.text = @"正在加载更多数据...";
    self.footerRefrshing = YES;
    [self loadMoreTopics];
}

- (void)footerEndRefrshing{
    self.footerRefrshing = NO;
    [self.footerIndicator stopAnimating];
    self.footerLabel.text = @"上拉可以加载更多";
}
@end
